<template>
  <!-- 右上角的悬浮分类过滤框 -->
  <div class="filter-category" v-if="categoryStore.selectedCategory">
    当前分类: {{ categoryStore.selectedCategory?.name }}
    <el-icon @click="clearFilter" class="cancel-icon">❌</el-icon>
  </div>

  <!-- 骨架屏 -->
  <el-skeleton :loading="isLoading" animated class="note-box">
    <template #template>
      <!-- 调整骨架屏样式，使其符合正文大小和样式 -->
      <div class="note-card skeleton" v-for="item in 10">
        <div class="note-content">
          <el-skeleton-item variant="image" class="skeleton-image" />
          <el-skeleton-item variant="text" class="skeleton-title" />
          <el-skeleton-item variant="text" class="skeleton-summary" />
          <el-skeleton-item variant="text" class="skeleton-stats" />
        </div>
      </div>
    </template>

    <!-- 正常内容 -->
    <div class="note-list" v-if="notes.length > 0">
      <div v-for="note in notes" :key="note.id" class="note-card" @click="goToDetail(note.id)">
         <div v-if="note.cover_image_url&&!isLargeScreen">
          <el-image class="note-cover" :src="note.cover_image_url" fit="cover" alt="笔记封面" />
        </div>
        <!-- 笔记内容 -->
        <div class="note-content">
          <!-- 用户信息 -->
          <div class="note-user">
            <el-avatar :size="30" :src="note.user.avatar_url || defaultAvatar" />
            <span class="user-name">{{ note.user.username }}</span>
          </div>
          <!-- 笔记标题 -->
          <h3 class="note-title">{{ note.title }}</h3>
          <!-- 笔记摘要 -->
          <div class="note-summary">{{ note.summary }}</div>
          <!-- 标签列表 -->
          <div v-if="note.category_readable" class="note-category">
            <div>分类：{{ note.category_readable.name }}</div>
          </div>
          <!-- 点赞数和评论数 -->
          <div class="note-stats">
            <span class="like-count">{{ note.like_count }} 👍</span>
            <span class="comments-count">{{ note.comments_count }} 💬</span>
          </div>
          <!-- 笔记分类 -->
          <div v-if="note.created_at" class="note-data">
            <div>{{ formatTime(note.created_at, 'YYYY-MM-DD') }}</div>
            <div class="note-tags">
              <el-tag v-for="tag in note.tags_readable" :key="tag" class="note-tag">{{ tag }}</el-tag>
            </div>
          </div>
        </div>

        <!-- 笔记封面（如果有的话） -->
        <div v-if="note.cover_image_url&&isLargeScreen">
          <el-image class="note-cover" :src="note.cover_image_url" fit="cover" alt="笔记封面" />
        </div>
      </div>
    </div>
  </el-skeleton>

  <!-- 分页组件 -->
  <el-pagination
    class="pagination"
    v-if="totalNotes > 0"
    :current-page="currentPage"
    :page-size="pageSize"
    :total="totalNotes"
    @current-change="handlePageChange"
    layout="prev, pager, next, jumper"
    background
  />
</template>

<script setup lang="ts">
import { ref, onMounted,watch } from 'vue';
import defaultAvatar from "@/assets/img/default_avatar.png";
import { getAction, postAction } from '@/api/manage';
import { Data } from '@/api/ajaxUrl.config';
import { useCategoryStore } from "@/stores/counter";
import { formatTime } from "@/utils/utils";
import { useRouter } from "vue-router";
import { useSearchStore } from '@/stores/counter';  // 引入你的 search store


const isLoading = ref(true); // 控制骨架屏的加载状态


const isLargeScreen = ref<boolean>(false)

// 监测屏幕大小变化，判断是否为移动端
const handleResize = () => {
  console.log(window.innerWidth)
  isLargeScreen.value = window.innerWidth >= 768;
};


const searchStore = useSearchStore();  // 获取搜索 store
const search = ref('')
// 监听搜索参数变化
watch(() => searchStore.searchText, (newValue) => {
  search.value = newValue;  // 将 searchStore.searchText 的变化同步到 search
  fetchNotes(1)
});



const categoryStore = useCategoryStore();  // 使用 categoryStore
const router = useRouter();
const notes = ref([]);
const totalNotes = ref(0);  // 总笔记数
const currentPage = ref(1);  // 当前页码
const pageSize = ref(10);  // 每页笔记数量

// 根据分类 ID 获取笔记
const fetchNotesByCategory = (categoryId: number, page: number) => {
  isLoading.value = true;  // 开启骨架屏
  getAction(Data.notes, { category: categoryId, page, pageSize: pageSize.value,search: search.value }).then((res: any) => {
    notes.value = res.results;
    totalNotes.value = res.count;  // 总记录数
    isLoading.value = false;  // 关闭骨架屏
  }).catch(() => {
    isLoading.value = false;  // 关闭骨架屏（请求失败）
  });
};

// 跳转笔记详情
const goToDetail = (id: number) => {
  let data = {
    note_id: id,
    action: '浏览了笔记'
  };
  postAction(Data.history, data).then((res: any) => {});
  router.push({ name: 'noteDetail', params: { id } });
};

// 清除分类过滤
const clearFilter = () => {
  categoryStore.clearCategory();  // 清除分类过滤
  fetchNotes(currentPage.value);  // 获取所有笔记
};

// 获取所有笔记
const fetchNotes = (page: number) => {
  isLoading.value = true;  // 开启骨架屏
  getAction(Data.notes, { page, pageSize: pageSize.value,search: search.value }).then((res: any) => {
    notes.value = res.results;
    totalNotes.value = res.count;  // 总记录数
    isLoading.value = false;  // 关闭骨架屏
  }).catch(() => {
    isLoading.value = false;  // 请求失败时关闭骨架屏
  });
};
// 处理分页变更
const handlePageChange = (newPage: number) => {
  currentPage.value = newPage;
  if (categoryStore.selectedCategory) {
    fetchNotesByCategory(categoryStore.selectedCategory.id, newPage);  // 分类下的笔记分页
  } else {
    fetchNotes(newPage);  // 所有笔记分页
  }
};

// 页面加载时检查是否有选中的分类
onMounted(() => {
   handleResize();
  window.addEventListener('resize', handleResize);
  if (categoryStore.selectedCategory) {
    fetchNotesByCategory(categoryStore.selectedCategory.id, currentPage.value);  // 如果有分类，按分类过滤
  } else {
    fetchNotes(currentPage.value);  // 否则获取所有笔记
  }
});
</script>

<style scoped lang="less">
/* 引入水墨风字体 */
@import url('https://fonts.googleapis.com/css2?family=Zhi+Mang+Xing&display=swap');
.note-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 20px 50px;
  max-width: 1200px;
  margin: 0 auto;
  overflow-y: auto;
}
.note-box{
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 20px 50px;
  max-width: 1200px;
  margin: 0 auto;
  overflow-y: auto;
}

.user-name {
  font-size: 14px;
  color: var(--color-text-muted);
  margin-left: 10px;
}

.note-card {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);
  background-color: var(--color-background-soft);
  transition: transform 0.3s ease;
  cursor: pointer;
}

.note-card:hover {
  transform: translateY(-5px);
}

.note-content {
  flex: 1;
  padding-right: 20px;
}

:deep(.el-image) {
  width: 230px;
  height: 170px;
  object-fit: cover;
  border-radius: 8px;
}

.note-user {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.note-title {
  font-size: 18px;
  font-weight: bold;
  padding-bottom: 10px;
  border-bottom: 1px solid var(--color-border);
}

.note-category {
  font-size: 14px;
  color: var(--color-text-muted);
  margin-bottom: 10px;
}

.note-tags {
  display: flex;
  gap: 5px;
  margin-bottom: 10px;
}

.note-tag {
  background-color: #f3f3f3;
  font-size: 12px;
}

.note-stats {
  display: flex;
  gap: 20px;
  font-size: 14px;
  color: var(--color-text-muted);
  margin-bottom: 10px;
}

.like-count,
.comments-count {
  display: inline-flex;
  align-items: center;
  gap: 5px;
}

.note-summary {
  margin: 10px 0;
}

/* 骨架屏样式 */
.skeleton .note-content {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.skeleton-image {
  width: 230px;
  height: 170px;
  border-radius: 8px;
}

.skeleton-title {
  height: 24px;
  width: 60%;
  margin-bottom: 10px;
}

.skeleton-summary {
  height: 18px;
  width: 50%;
}

.skeleton-stats {
  height: 14px;
  width: 40%;
}

/* 分类过滤内容样式 */
.filter-category {
  position: fixed;
  top: 120px;
  right: 80px;
  z-index: 9999;
  display: flex;
  align-items: center;
  background-color: var(--color-background-soft);
  padding: 10px;
  border-radius: 8px;
  box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);
}

/* 取消过滤的图标样式 */
.cancel-icon {
  margin-left: 10px;
  cursor: pointer;
  color: #f56c6c;
  font-size: 16px;
}

.pagination {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 针对小屏设备 (手机) */
@media (max-width: 767px) {
  /* 小屏样式 */
  .note-list,.note-box{
  display: flex;
  flex-direction: column;
  padding: 10px 10px;
  overflow-y: auto;
  }

  .note-card {
  display: flex;
  flex-direction: column;
  //justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);
  background-color: var(--color-background-soft);
  transition: transform 0.3s ease;
  cursor: pointer;
}
  .note-content {
  flex: 1;
    width: 100%;
  padding-right: 20px;
}
}
</style>
